package com.vf.admin.client.service.impl;

import com.vf.admin.client.dao.AppGuardDao;
import com.vf.admin.client.dao.AppIntimacyGuardDao;
import com.vf.admin.client.dao.AppSetupDao;
import com.vf.admin.client.dao.AppUserDao;
import com.vf.admin.client.service.AppGuardService;
import com.vf.admin.client.service.SystemAlertService;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.entity.AppGuard;
import com.vf.admin.miaodong.entity.AppIntimacyGuard;
import com.vf.admin.miaodong.entity.AppSetup;
import com.vf.admin.miaodong.entity.AppUser;
import com.vf.admin.utils.AgeUtils;
import com.vf.admin.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class AppGuardServiceImpl implements AppGuardService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AppGuardDao appGuardDao;
    @Autowired
    private AppUserDao appUserDao;
    @Autowired
    private AppIntimacyGuardDao appIntimacyGuardDao;
    @Autowired
    private AppSetupDao appSetupDao;
    @Autowired
    private SystemAlertService systemAlertService;

    @Override
    public List<AppGuard> getMyGuardInfo(Integer userId) {
        List<AppGuard> myGuardInfo = appGuardDao.getMyGuardInfo(userId);
        if (myGuardInfo != null && myGuardInfo.size() > 0) {
            myGuardInfo.forEach(e -> {
                AppUser appUser = appUserDao.get(e.getBeiUserId());
                if (appUser != null) {
                    e.setPic(appUser.getPic());
                    e.setNick(appUser.getNick());
                    e.setSex(appUser.getSex());
                    e.setYearOld(AgeUtils.getAgeByBirth(appUser.getBirthday()));
                    int days = AgeUtils.differentDays(e.getCreatetime(), new Date());
                    if (days <= 0) {
                        e.setDays(1);
                    } else {
                        e.setDays(days + 1);
                    }
                }
            });
            return myGuardInfo;
        }
        return null;
    }

    @Override
    public AppGuard guardForMe(Integer beiUserId) {
        AppGuard guardInfo = appGuardDao.getGuardInfo(beiUserId);
        if (guardInfo != null) {
            AppUser appUser = appUserDao.get(guardInfo.getUserId());
            guardInfo.setPic(appUser.getPic());
            guardInfo.setNick(appUser.getNick());
            guardInfo.setSex(appUser.getSex());
            guardInfo.setYearOld(AgeUtils.getAgeByBirth(appUser.getBirthday()));
            int days = AgeUtils.differentDays(guardInfo.getCreatetime(), new Date());
            if (days <= 0) {
                guardInfo.setDays(1);
            } else {
                guardInfo.setDays(days + 1);
            }
            return guardInfo;
        }

        return null;
    }


    @Transactional(rollbackFor = Exception.class)
    public void decIntimacy() {
        try {
            AppSetup setup = appSetupDao.get();
            if (setup.getDecIntimacyForHours().compareTo(BigDecimal.ZERO) > 0 && setup.getDecIntimacyForNum().compareTo(BigDecimal.ZERO) > 0) {
                List<AppGuard> allGuardList = appGuardDao.getAllGuardList();
                if (allGuardList != null && allGuardList.size() > 0) {
                    for (AppGuard guard : allGuardList) {
                        if (guard.getIntimacy().compareTo(setup.getMaxintimacy()) < 0) {
                            List<AppIntimacyGuard> hoursIntimacyList = appIntimacyGuardDao.getHoursIntimacyList(setup.getDecIntimacyForHours(), guard.getUserId(), guard.getBeiUserId());
                            if (hoursIntimacyList == null || hoursIntimacyList.size() <= 0) {
                                BigDecimal jianMoney = setup.getDecIntimacyForNum().divide(setup.getIntimacyZuanshi());
                                appGuardDao.updateIntimacyAndGiftMoney(guard.getId(), setup.getDecIntimacyForNum(), jianMoney);

                                //原先是守护,判断降低亲密度后是否还能维持守护
                                if (guard.getIsGuard() == 1) {
                                    BigDecimal subtract = guard.getIntimacy().subtract(setup.getDecIntimacyForNum());
                                    if (subtract.compareTo(setup.getIntimacyGuard()) >= 0) {
                                        AppGuard maxIntimacyInfo = appGuardDao.getMaxIntimacyInfo(guard.getBeiUserId());
                                        if (maxIntimacyInfo != null) {
                                            if (maxIntimacyInfo.getIntimacy().compareTo(subtract) > 0) {
                                                appGuardDao.updateGuardById(maxIntimacyInfo.getId(), 1);
                                                appGuardDao.updateGuardById(guard.getId(), 2);

                                                //亲密度降低发送通知
                                                AppUser user = appUserDao.get(guard.getUserId());
                                                AppUser beUser = appUserDao.get(guard.getBeiUserId());
                                                systemAlertService.sendQMT_DOWN(user.getTengxuncode(), beUser.getNick(), setup.getDecIntimacyForNum().toPlainString());
                                            }
                                        }
                                    } else {
                                        AppGuard maxIntimacyInfo = appGuardDao.getMaxIntimacyInfo(guard.getBeiUserId());
                                        if (maxIntimacyInfo != null) {
                                            if (maxIntimacyInfo.getIntimacy().compareTo(setup.getIntimacyGuard()) >= 0) {
                                                appGuardDao.updateGuardById(maxIntimacyInfo.getId(), 1);
                                            }
                                        }
                                        appGuardDao.updateGuardById(guard.getId(), 2);
                                    }

                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("降低亲密度异常：", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }


    /**
     * 查看用户是否有守护
     *
     * @param beiUserId
     * @return
     */
    @Override
    public AppGuard isGuardInfo(Integer beiUserId) {
        AppSetup setup = appSetupDao.get();
        AppGuard guardInfo = appGuardDao.getGuardInfo(beiUserId);
        if (guardInfo == null) {
            AppGuard appGuard = new AppGuard();
            appGuard.setIsHaveGuard(2);
            appGuard.setPayMoney(setup.getIntimacyGuard().divide(setup.getIntimacyZuanshi()));
            return appGuard;
        } else {
            AppUser appUser = appUserDao.get(guardInfo.getUserId());
            guardInfo.setPic(appUser.getPic());
            guardInfo.setNick(appUser.getNick());
            guardInfo.setSex(appUser.getSex());
            guardInfo.setYearOld(AgeUtils.getAgeByBirth(appUser.getBirthday()));
            BigDecimal payMoney = guardInfo.getGiftMoney().add(guardInfo.getGiftMoney().multiply(setup.getGuardZeng()));
            guardInfo.setPayMoney(payMoney);
            int days = AgeUtils.differentDays(guardInfo.getCreatetime(), new Date());
            if (days <= 0) {
                guardInfo.setDays(1);
            } else {
                guardInfo.setDays(days + 1);
            }
            guardInfo.setIsHaveGuard(1);
            return guardInfo;
        }
    }

    @Override
    public List<AppGuard> intimacyGuardList(Integer beiUserId) {
        List<AppGuard> appGuards = appGuardDao.intimacyGuardList(beiUserId);
        if (appGuards != null && appGuards.size() > 0) {
            appGuards.forEach(e -> {
                AppUser appUser = appUserDao.get(e.getUserId());
                if (appUser != null) {
                    e.setPic(appUser.getPic());
                    e.setNick(appUser.getNick());
                    e.setSex(appUser.getSex());
                    e.setYearOld(AgeUtils.getAgeByBirth(appUser.getBirthday()));
                    int days = AgeUtils.differentDays(e.getCreatetime(), new Date());
                    if (days <= 0) {
                        e.setDays(1);
                    } else {
                        e.setDays(days + 1);
                    }
                    if (appUser.getVipEndDate() != null) {
                        e.setIsVip(TimeUtils.afterNow(appUser.getVipEndDate())? 1: 0);
                    }
                }
            });
            return appGuards;
        }
        return null;
    }

    @Override
    public AppGuard toGuard(Integer beiUserId) {
        AppSetup setup = appSetupDao.get();
        AppGuard guardInfo = appGuardDao.getGuardInfo(beiUserId);
        AppUser appUser = appUserDao.get(beiUserId);
        if (guardInfo == null) {
            AppGuard appGuard = new AppGuard();
            appGuard.setPayMoney(setup.getIntimacyGuard().divide(setup.getIntimacyZuanshi()));
            appGuard.setPic(appUser.getPic());
            appGuard.setNick(appUser.getNick());
            return appGuard;
        } else {
            BigDecimal payMoney = guardInfo.getGiftMoney().add(guardInfo.getGiftMoney().multiply(setup.getGuardZeng()));
            guardInfo.setNick(appUser.getNick());
            guardInfo.setPic(appUser.getPic());
            guardInfo.setPayMoney(payMoney);
            return guardInfo;
        }
    }

    @Override
    public AppGuard getGuaardByUserId(Integer userId, Integer beiUserId) {
        return appGuardDao.getGuaardByUserId(userId, beiUserId);
    }

    @Override
    public boolean isEachGuild(Integer userId, Integer toUserId) {
        AppGuard guild = appGuardDao.isGuild(userId, toUserId);
        AppGuard guild1 = appGuardDao.isGuild(toUserId, userId);
        if (guild != null && guild1 != null) {
            return true;
        }
        return false;
    }

    @Override
    public List<AppGuard> getIntimacyList(SplitPageBean splitPageBean, Integer userId) {
        List<AppGuard> intimacyList = appGuardDao.getIntimacyList(splitPageBean, userId);
        if (intimacyList != null && intimacyList.size() > 0) {
            intimacyList.forEach(e -> {
                AppUser appUser = appUserDao.get(e.getBeiUserId());
                e.setUserNameA(appUser.getNick());
                e.setUserPhoneA(appUser.getLoginname());
                e.setPic(appUser.getPic());
                e.setSex(appUser.getSex());
                int days = AgeUtils.differentDays(e.getCreatetime(), new Date());
                if (days <= 0) {
                    e.setDays(1);
                } else {
                    e.setDays(days + 1);
                }
            });
            return intimacyList;
        }
        return null;
    }


    @Override
    public List<AppGuard> guardList(SplitPageBean splitPageBean, AppGuard appGuard) {
        List<AppGuard> appGuards = appGuardDao.guardList(splitPageBean, appGuard);
        if (appGuards != null && appGuards.size() > 0) {
            appGuards.forEach(e -> {
                AppUser appUser = appUserDao.get(e.getUserId());
                e.setUserNameA(appUser.getNick());
                e.setUserPhoneA(appUser.getLoginname());
                AppUser appUser1 = appUserDao.get(e.getBeiUserId());
                e.setUserNameB(appUser1.getNick());
                e.setUserPhoneB(appUser1.getLoginname());
                int days = AgeUtils.differentDays(e.getCreatetime(), new Date());
                if (days <= 0) {
                    e.setDays(1);
                } else {
                    e.setDays(days + 1);
                }
            });
            return appGuards;
        }
        return null;
    }


}
